package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.annotaion.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.*;
import com.sky.enumeration.OperationType;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishStopFailedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Override
    @Transactional
    @AutoFill(value = OperationType.INSERT)
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);
        Long dishId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();

        if (flavors != null && flavors.size() > 0) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishId);
                dishFlavorMapper.insert(flavor);
            }
        }
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        Page<Dish> page = new Page<>(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> voPage = new Page<>();



        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(dishPageQueryDTO.getName() != null && dishPageQueryDTO.getName() != "",
                Dish::getName, dishPageQueryDTO.getName());
        lambdaQueryWrapper.like(dishPageQueryDTO.getStatus() != null,
                Dish::getStatus, dishPageQueryDTO.getStatus());
        lambdaQueryWrapper.like(dishPageQueryDTO.getCategoryId() != null,
                Dish::getCategoryId, dishPageQueryDTO.getCategoryId());
        lambdaQueryWrapper.orderByDesc(Dish::getCreateTime);
        dishMapper.selectPage(page, lambdaQueryWrapper);

        BeanUtils.copyProperties(page, voPage, "records");
        List<Dish> records = page.getRecords();
        List<DishVO> list = records.stream().map((item) -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(item, dishVO);
            Long categoryId = item.getCategoryId();
            Category category = categoryMapper.selectById(categoryId);
            String name = category.getName();

            dishVO.setCategoryName(name);
            return dishVO;
        }).collect(Collectors.toList());

        voPage.setRecords(list);
        return new PageResult(voPage.getTotal(), voPage.getRecords());
    }

    @Transactional
    @Override
    public void deleteBatch(List<Long> ids) {
        ids.forEach(id->{
            Dish dish = dishMapper.selectById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });
        /*for (Long id : ids) {
            Dish dish = dishMapper.selectById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }*/
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0) {


            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);

        }
        dishMapper.deleteBatchIds(ids);

        dishFlavorMapper.deleteByDishIds(ids);

    }

    @Override
    public DishVO getByIdwithFlavor(Long id) {
        Dish dish = dishMapper.selectById(id);
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    @Transactional
    @AutoFill(value = OperationType.UPDATE)
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.updateById(dish);

        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishDTO.getId());
                dishFlavorMapper.insert(flavor);
            }
        }

    }

    @Override
    public List<Dish> list(Long categoryId) {
        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", categoryId).eq("status", StatusConstant.ENABLE);
        List<Dish> dishes = dishMapper.selectList(wrapper);
        // List<Dish> dishes= dishMapper.listByCategoryId(categoryId);
        return dishes;
    }
    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", dish.getCategoryId()).eq("status", StatusConstant.ENABLE);
        List<Dish> dishList = dishMapper.selectList(wrapper);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        /*QueryWrapper<SetmealDish> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dish_id",id);*/
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SetmealDish::getDishId,id);
        SetmealDish setmealDish = setmealDishMapper.selectOne(lambdaQueryWrapper);
        if(setmealDish != null){
            //菜品被套餐关联，不能被停售
            throw new DishStopFailedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();


        dishMapper.updateById(dish);

    }

}